const OrderMenuConfig = {
	ITEM_CLASS: 'order-menu-item',
	ITEM_ICON: "img/ic_order_to_pay.png"
}

class OrderMenu {
	constructor(options) {
		this.data = options.data;
		this.container = document.querySelector(options.container);
		this.onClickItem = options.onClickItem || function() {}
		this.render();
		this.bindEvents();
	}

	render() {
		this.container.innerHTML = '';
		const html = this.data.map((item, index) =>
			this.generateTabItem(item, index)
		).join('');
		this.container.innerHTML = html;
	}

	generateTabItem(e, index) {
		let num = e.value;
		const bagde = num && parseInt(num) ? `<span class="badge">${num}</span>` : ``;
		return `<div class="${OrderMenuConfig.ITEM_CLASS}" data-item='${escapeHtml(JSON.stringify(e))}'>
					<div style="position:relative;">
						${bagde}
						<img src="${getRootPath() + (e.icon || MenuConfig.ITEM_ICON)}"/>
					</div>
					${e.label}
				</div>`;
	}

	bindEvents() {
		//纯原生写法，不依赖jquery
		this.container.addEventListener('click', e => {
			const itemElement = e.target.closest(`.${OrderMenuConfig.ITEM_CLASS}`);
			if (itemElement) {
				try {
					const itemData = JSON.parse(itemElement.dataset.item);
					this.onClickItem(itemData);
				} catch (error) {
					console.error('解析item数据失败:', error);
				}
			}
		})
	}

	update(newData) {
		this.data = newData;
		this.render();
	}
}
